package com.asd.map.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.asd.common.Result;
import com.asd.config.IdGenerator;
import com.asd.map.entity.*;
import com.asd.map.entity.vo.Line_surfaceVo;
import com.asd.map.entity.vo.Point_positionVo;
import com.asd.map.service.*;
import com.asd.system.entity.User;
import com.asd.system.service.IUserService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/map")
@Api(tags = "应用Api")
public class ApplyController {

    @Autowired
    private ApplyService applyService;

    @Autowired
    private IInformationService iInformationService;
    @Autowired
    private IPoint_positionService point_positionService;

    @Autowired
    private ILine_surfaceService line_surfaceService;

    @Autowired
    private IPoint_styleService point_styleService;

    @Autowired
    private ILine_styleService line_styleService;

    @Autowired
    private ISurface_styleService surface_styleService;

    @Autowired
    private ITagging_styleService tagging_styleService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IdGenerator idGenerator;

    //添加应用数据
    @ApiOperation(value = "添加应用数据", notes = "添加应用数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mapName", value = "应用名称", required = true),
            @ApiImplicitParam(name = "userId", value = "用户id", required = true),
            @ApiImplicitParam(name = "mapLable", value = "应用标签"),
            @ApiImplicitParam(name = "mapDesc", value = "应用描述"),
            @ApiImplicitParam(name = "mapLink", value = "应用图片")
    })
    @PostMapping("/addApply")
    public Result<?> addApply(@RequestParam("userId") String userId, @RequestParam("mapName") String mapName, @RequestParam("mapLable") String mapLable,
                              @RequestParam("mapDesc") String mapDesc, @RequestParam("mapName") String mapLink) {
        //public Result<?> addApply(@RequestBody Map_apply apply){


        Map_apply apply = new Map_apply();

        String id = idGenerator.nextId();
        apply.setId(id);
        apply.setMap_name(mapName);
        apply.setMap_lable(mapLable);
        apply.setMap_desc(mapDesc);
        apply.setMap_link(mapLink);
        //applyService.addApply(apply);
        applyService.save(apply);
        //applyService.addApply(apply);


        User user = userService.getById(userId);

//        //获取本用户所有的应用id
//        String dataApp = user.getDataApp();
        if (user.getDataApp() == null || user.getDataApp().equals("")) {
            List<String> list = new ArrayList<>();
            list.add(id);
            String str = JSON.toJSONString(list);
            user.setDataApp(str);
            userService.updateById(user);

        } else {
            List<String> listAppiyId = (List<String>) JSONArray.parse(user.getDataApp());
            listAppiyId.add(id);
            String str = JSON.toJSONString(listAppiyId);
            user.setDataApp(str);
            userService.updateById(user);
        }

        return Result.ok(apply);
    }

    /**
     * 根据id删除应用数据
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "删除应用数据", notes = "删除")
    @DeleteMapping("/delApply")
    public Result<?> delApply(@RequestParam("id") String id, @RequestParam("userId") String userId) {

        //删除应用对应的点线面样式
        applyService.deleteStyleById(id);

        User user = userService.getById(userId);
        if (StringUtils.isNotEmpty(user.getDataApp())) {
            List<String> listAppiyId = (List<String>) JSONArray.parse(user.getDataApp());
            listAppiyId.remove(id);
            String str = JSON.toJSONString(listAppiyId);
            user.setDataApp(str);
            userService.updateById(user);
        }

        applyService.removeById(id);

        return Result.ok("删除成功");
    }

    /**
     * 修改应用数据
     * //     * @param id
     * //     * @param mapName
     * //     * @param mapLable
     * //     * @param mapDesc
     * //     * @param mapLink
     *
     * @return
     */
    @ApiOperation(value = "修改应用数据", notes = "修改应用数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true),
            @ApiImplicitParam(name = "mapName", value = "应用名称"),
            @ApiImplicitParam(name = "mapLable", value = "应用标签"),
            @ApiImplicitParam(name = "mapDesc", value = "应用描述"),
            @ApiImplicitParam(name = "mapLink", value = "应用图片")
    })
    @PutMapping("/updateApply")
    public Result<?> updateApply(String id, String mapName, String mapLable, String mapDesc, String mapLink) {
        //public Result<?> updateApply(@RequestBody Map_apply apply){


        Map_apply apply = new Map_apply();

        apply.setId(id);
        apply.setMap_name(mapName);
        apply.setMap_lable(mapLable);
        apply.setMap_desc(mapDesc);
        apply.setMap_link(mapLink);
        applyService.updateById(apply);
        //applyService.updateApply(apply);

        return Result.ok("修改成功");
    }

    @ApiOperation(value = "根据应用id修改data值", notes = "根据应用id修改data值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "应用id", required = true),
            @ApiImplicitParam(name = "data", value = "data", required = true)
    })
    @PutMapping("/updateDataById")
    public Result<?> updateDataById(@RequestParam("id") String id, @RequestParam("data") String data) {

        Map_apply apply = applyService.getById(id);

        apply.setData(data);

        applyService.updateById(apply);

        return Result.ok("修改成功");
    }


    //应用数据分页查询
    @ApiOperation(value = "应用数据-分页查询", notes = "应用数据-分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "当前页"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小")
    })
    @GetMapping("/queryPageList")
    public Result<Object> queryPageList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                        @RequestParam(name = "pageSize", defaultValue = "5") Integer pageSize) {
        Page<Map_apply> page = new Page<Map_apply>(pageNo, pageSize);

        List<Map_apply> list = applyService.selectApplyPage(page);

        Page<Map_apply> pageList = page.setRecords(list);


        return Result.ok(pageList);

    }

    //应用中所用数据源和点位信息查询
    @ApiOperation(value = "应用数据-数据源和点位信息查询", notes = "应用数据-数据源和点位信息查询")
    @GetMapping("/queryDataList")
    public Result<Object> queryDataList(@RequestParam("id") String id) {
        Information information = new Information();
        List<Map_Information_point> mipList = new ArrayList<>();
        Map_apply apply = applyService.getById(id);
        String data = apply.getData();

        if (!(data == null || data.equals("") || data.length() == 0)) {
            List<Map<String, String>> listObjectFir = (List<Map<String, String>>) JSONArray.parse(data);
            for (int i = 0; i < listObjectFir.size(); i++) {

                Map_Information_point map_information_point = new Map_Information_point();
                //获取数据源id
                String did = listObjectFir.get(i).get("id");
                //获取图层id
                String tid = listObjectFir.get(i).get("tid");
                //获取图层状态
                String ishow = String.valueOf(listObjectFir.get(i).get("ishow"));

                map_information_point.setId(did);
                map_information_point.setTid(tid);
                map_information_point.setIshow(ishow);
                information.setId(did);
                //通过did查询数据源对应信息
                try {//数据源存在时执行
                    Information information1 = iInformationService.getById(information);
                    map_information_point.setCreate_time(information1.getCreate_time());
                    map_information_point.setData(information1.getData());
                    map_information_point.setName(information1.getName());
                    map_information_point.setType(information1.getType());
                    map_information_point.setAddtype(information1.getAddtype());
                    //map_information_point.setLink(information1.getLink());
                    map_information_point.setIsImage(information1.getIsImage());
                    //String link = information1.getLink();


                } catch (Exception e) {//数据源已经被删除时执行

                    listObjectFir.remove(i);
                    String str = JSON.toJSONString(listObjectFir);
                    applyService.updateById1(str, id);
                }

                //通过did对应点位信息
                List<Point_positionVo> pointPositionVos = point_positionService.getByDid1(did, id);
//                System.out.println(pointPositionVos);

                if (!pointPositionVos.isEmpty()) {
                    map_information_point.setPointPositionVos(pointPositionVos);
                }

                //通过did对应线面信息
                List<Line_surfaceVo> line_surfaceVos = line_surfaceService.getByDid(id, did);
                if (!line_surfaceVos.isEmpty()) {
                    map_information_point.setLine_surfaceVos(line_surfaceVos);
                }
                //通过图层id获取标注样式
                Tagging_style taggingStyle = tagging_styleService.findBYTid(tid);
                map_information_point.setTagging_style(taggingStyle);

                mipList.add(map_information_point);
            }

            return Result.ok(mipList);
        }else {
            return Result.ok("该应用暂无数据！");
        }

    }

    @ApiOperation(value = "视野保存", notes = "视野保存")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true),
            @ApiImplicitParam(name = "view", value = "视野"),
    })
    @PutMapping("/updetViewById")
    public Result<Object> updetViewById(@RequestParam("id") String id, @RequestParam("view") String view) {

        applyService.updetViewById(id, view);

        return Result.ok();
    }

    @ApiOperation(value = "修改底图", notes = "修改底图")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true),
            @ApiImplicitParam(name = "baseLayer", value = "底图"),
    })
    @PutMapping("/changeBaseLayer")
    public Result<Object> changeBaseLayer(@RequestParam("id") String id, @RequestParam("baseLayer") String baseLayer) {

        applyService.changeBaseLayer(id, baseLayer);

        return Result.ok();
    }

    //根据用户查询应用数据
    @ApiOperation(value = "应用数据-根据用户ID查询应用数据", notes = "应用数据-根据用户ID查询应用数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id"),
            @ApiImplicitParam(name = "pageNo", value = "当前页"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小")
    })
    @GetMapping("/queryApplyByUserId")
    public Result<Object> queryApplyByUserId(@RequestParam("userId") String userId,
                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                             @RequestParam(name = "pageSize", defaultValue = "5") Integer pageSize) {

        ArrayList<Map_apply> mipList = new ArrayList<>();

        User user = userService.getById(userId);
        //获取本用户所有的应用id
//        String dataApp = user.getDataApp();

        if (StringUtils.isNotEmpty(user.getDataApp())) {

            List<String> listAppiyId = (List<String>) JSONArray.parse(user.getDataApp());
            for (int i = 0; i < listAppiyId.size(); i++) {
                Map_apply map_apply = applyService.getById(listAppiyId.get(i));
                mipList.add(map_apply);
            }

//            //将mipList分页并返回
//            Page page = new Page();
//            int size = mipList.size();
//            if (pageSize > size) {
//                pageSize = size;
//            }
//            //求出最大页数，防止pageNo越界
//            int maxPage = size % pageSize == 0 ? size / pageSize : size / pageSize + 1;
//            if (pageNo > maxPage) {
//                pageNo = maxPage;
//            }
//            //当前页第一条数据下标
//            int curIds = pageNo > 1 ? (pageNo - 1) * pageSize : 0;
//
//            List pageList = new ArrayList<>();
//
//            //将当前页的数据放进pageList
//            for (int i = 0; i < pageSize && curIds + i < size; i++) {
//                pageList.add(mipList.get(curIds + i));
//            }
//            page.setCurrent(pageNo).setSize(pageSize).setTotal(mipList.size()).setRecords(pageList);
            return Result.ok(mipList);
        } else {
            return Result.ok("该用户暂无应用,请添加！");
        }
    }


    /**
     * 点线面分页模糊查询
     *
     * @param
     * @param
     * @param 
     * @return
     */
    @ApiOperation(value = "点线面分页模糊查询", notes = "点线面分页模糊查询")
    @GetMapping(value = "/dataList")
    public Result<?> queryPageDataList(@RequestParam("data") String data) {

        List<Line_surface> surfaceList = line_surfaceService.queryByData(data);
        List<Point_position> positionList = point_positionService.queryByData(data);

        List<Object> list = new ArrayList<>();

        if (surfaceList.size()>0){
            for (Line_surface line_surface:surfaceList) {
                list.add(line_surface);
            }
        }

        if (positionList.size()>0){
            for (Point_position point_position:positionList) {
                list.add(point_position);
            }
        }


        return Result.ok(list);
    }

}
